package com.taobao.dao.impl;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.taobao.dao.CommonDao;
import com.taobao.dao.HistoryTaskDao;
import com.taobao.pojo.Config;
import com.taobao.pojo.ConfirmTime;
import com.taobao.pojo.Equals;
import com.taobao.pojo.HttpContext;
import com.taobao.pojo.Page;
import com.taobao.pojo.State;
import com.taobao.pojo.Task;

public class HistoryTaskDaoImpl extends CommonDao implements HistoryTaskDao {
	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

	@SuppressWarnings("unchecked")
	@Override
	public List<Task> historySerach(String[] ve, Task last) throws Exception {
		List<Task> all = new ArrayList<Task>();

		Map<String, String> params = new HashMap<String, String>();
		params.put("__VIEWSTATE", ve[0]);
		params.put("__EVENTVALIDATION", ve[1]);
		params.put("fTimeStartTxt", sdf.format(twoMonthAgo(Config.now)));
		params.put("fTimeEndTxt", sdf.format(Config.now));
		params.put("jorfDDL", "j");
		params.put("SearchBtn", "查询");
		params.put("sTypeDDL", "t");

		params.put("jSmallUserTxt", "");
		params.put("fUserNameTxt", "");
		params.put("jUserNameTxt", "");
		params.put("tidTxt", "");

		Map<String, Object> map = (Map<String, Object>) postRequest(Config.url + "TasksHis_Search.aspx", null, params);
		Page page = (Page) map.get("page");
		List<Task> tasks = (List<Task>) map.get("tasks");
		ve = (String[]) map.get("ve");
		all.addAll(tasks);

		params.put("__EVENTTARGET", "nextPageLBtn");
		params.put("__EVENTARGUMENT", "");
		params.put("GoPageIndexTxt", "");
		params.remove("SearchBtn");
		while (!page.isLastPage() && !isStop(all, last)) {
			params.put("__VIEWSTATE", ve[0]);
			params.put("__EVENTVALIDATION", ve[1]);

			map = (Map<String, Object>) postRequest(Config.url + "TasksHis_Search.aspx", null, params);
			page = (Page) map.get("page");
			tasks = (List<Task>) map.get("tasks");
			ve = (String[]) map.get("ve");
			all.addAll(tasks);
		}

		return all;
	}

	@Override
	public Object process(HttpContext context) throws Exception {
		List<Task> tasks = new ArrayList<Task>();
		Document doc = Jsoup.parse(context.getHtml());
		Elements els = doc.getElementsByTag("tr");
		for (int i = 0; i < els.size(); i++) {
			Element ele = els.get(i);
			if ("this.style.backgroundColor='#fcefe3';".equals(ele.attr("onmouseover")) && "this.style.backgroundColor='#ffffff';".equals(ele.attr("onmouseout"))) {
				Elements tr = ele.getAllElements();
				tasks.add(this.trToTask(tr));
			}
		}

		Element pageEle = doc.getElementById("CurrentPageLbl");
		String pageStr = pageEle.text().trim();
		Page page = new Page(Integer.parseInt(pageStr.substring(0, pageStr.indexOf("/"))), Integer.parseInt(pageStr.substring(pageStr.indexOf("/") + 1)));

		String[] ve = new String[2];
		String vstr = doc.getElementById("__VIEWSTATE").attr("value");
		String estr = doc.getElementById("__EVENTVALIDATION").attr("value");

		ve[0] = vstr;
		ve[1] = estr;

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("page", page);
		map.put("tasks", tasks);
		map.put("ve", ve);
		return map;
	}

	private Date twoMonthAgo(Date now) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(now);
		calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 2);
		return calendar.getTime();
	}

	private Task trToTask(Elements tr) throws SecurityException, IllegalArgumentException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
		List<Element> tds = new ArrayList<Element>();
		Task task = new Task();
		for (int i = 0; i < tr.size(); i++) {
			Element td = tr.get(i);
			if ("td".equals(td.tagName())) {
				tds.add(td);
			}
		}
		this.setValue(tds, task);
		return task;
	}

	private void setValue(List<Element> tds, Task task) throws SecurityException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
		for (int i = 0; i < tds.size(); i++) {
			Method method;
			try {
				method = this.getClass().getMethod("td" + i, new Class[] { Element.class, Task.class });
				method.invoke(this, new Object[] { tds.get(i), task });
			} catch (NoSuchMethodException e) {
				System.err.println("没有此方法：  td" + i);
			}
		}
	}

	public void td0(Element td, Task task) {
		task.setState(new State(7));
	}

	public void td1(Element td, Task task) {
		String text = td.text().trim();
		task.setId(Long.parseLong(text.substring(0, text.indexOf(" "))));
		task.setPublishPoint(Double.parseDouble(text.substring(text.indexOf("：") + 1, text.indexOf("个"))));
	}

	public void td2(Element td, Task task) {
		String text = td.child(0).attr("value");
		task.setTbUrl(text);
	}

	public void td3(Element td, Task task) {
		String text = td.text().trim();
		task.setName(text.substring(0, text.indexOf(" ")));
		task.setTbName(text.substring(text.indexOf("：") + 1));
	}

	public void td4(Element td, Task task) {
		String text = td.text().trim();
		task.setSmallUser(text);
	}

	public void td5(Element td, Task task) {
		String text = td.text().trim();
		task.setPrice(Double.parseDouble(text.substring(1, text.indexOf(" "))));
		task.setEquals(new Equals(text.substring(text.indexOf(" ") + 1)));
	}

	public void td6(Element td, Task task) {
		String text = td.text().trim();
		task.setConfirmTime(new ConfirmTime(-1, text));
	}

	public void td7(Element td, Task task) {
		String text = td.text().trim();
		task.setPublishTime((task.getId() + "").substring(0, 4) + "-" + text);
	}

	public void td8(Element td, Task task) {
		td = td.child(0);
		String text = td.outerHtml();
		task.setHpWord(text.substring(text.indexOf("(") + 2, text.indexOf(")") - 1));
	}

	private boolean isStop(List<Task> tasks, Task last){
		boolean stop = false;
		for (Iterator<Task> iterator = tasks.iterator(); iterator.hasNext();) {
			Task task = (Task) iterator.next();
			if(last != null && task.getId() == last.getId()){
				stop = true;
			}
			if(stop){
				iterator.remove();
			}
		}
		return stop;
	}
}
